package cn.yunyichina.provider.sys.service.impl;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.sys.dao.*;
import cn.yunyichina.provider.sys.entity.Resource;
import cn.yunyichina.provider.sys.entity.Role;
import cn.yunyichina.provider.sys.entity.RoleResourceRelation;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by Administrator on 2018/1/26.
 */
@Service
public class RoleServiceImpl {

    private static Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private RoleResourceRelationDao resourceRelationDao;

    @Autowired
    private DeptUserRelationDao deptUserRelationDao;
    @Autowired
    private UserRoleRelationDao userRoleRelationDao;

    @Autowired ResourceServiceImpl resourceService;

    /**
     * 保存角色
     * @methodName: yyt.sys.role.save
     * @param data
     * @return
     */
    public Response saveRole(String data){
        Response response =new Response();
        Role requestVo  = JsonUtils.parseObject(data, Role.class);

        // 校验RequestVo的数据
//        try {
//            Validator.getInstance().validate(requestVo);
//        } catch (ValidateException ex) {
//            logger.error("error", ex);
//            response.setResultCodeAndMessage("1101", "数据校验失败:" + ex.getMessage() + "！");
//            return response;
//        }

        try{
            //查询是否存在相同编号的角色
            Role query = new Role();
            query.setRoleCode(requestVo.getRoleCode());
            List<Role> list = roleDao.select(query);
            if(list == null || list.size() == 0){
                //新增角色
                requestVo.setId(PKGenerator.generateId());
                requestVo.setCreatedTime(DateUtils.dateToString(new Date()));
                requestVo.setEnableFlag((short) 1);
                roleDao.insert(requestVo);
            }else{
                //更新角色
                requestVo.setId(list.get(0).getId());
                requestVo.setUpdateTime(DateUtils.dateToString(new Date()));
                roleDao.update(requestVo);
            }
            String resourceIds = requestVo.getResourseIds();
            if(StringUtils.isNotBlank(resourceIds)) {
                //批量插入角色资源关系,先删除该角色下的资源
                resourceRelationDao.deleteByRoleId(requestVo.getId());

                List<RoleResourceRelation> relationList = new ArrayList<>();
                List<String> ids = Arrays.asList(resourceIds.split(","));
//                List<Resource> resources = resourceDao.selectByIds(ids);
//                for (Resource res : resources) {
//                    RoleResourceRelation relation = new RoleResourceRelation();
//                    relation.setId(PKGenerator.generateId());
//                    relation.setRoleId(requestVo.getId());
//                    relation.setRoleName(requestVo.getRoleName());
//                    relation.setResourceId(res.getId());
//                    relation.setResourceName(res.getResourceName());
//                    relationList.add(relation);
//                }
                for(String idItem:ids){
                    String[] idStr = idItem.split("_");
                    Resource resource = resourceDao.selectById(idStr[0]);
                    if(resource != null && idStr.length > 1) {
                        RoleResourceRelation relation = new RoleResourceRelation();
                        relation.setId(PKGenerator.generateId());
                        relation.setRoleId(requestVo.getId());
                        relation.setRoleName(requestVo.getRoleName());
                        relation.setResourceId(resource.getId());
                        relation.setResourceName(resource.getResourceName());
                        relation.setAuth(idStr[1]);
                        relationList.add(relation);
                    }
                }

                if(relationList.size() > 0) {
                    resourceRelationDao.batchInsert(relationList);
                }
            }

            response.setResultCodeAndMessage("0","保存成功");

        }catch (Exception e){
            response.setResultCodeAndMessage("-1","保存失败" + e.getMessage());
        }
        return  response;
    }


    /**
     * 获取角色列表 yyt.sys.role.list
     * @param data
     * @return
     */
    public Response listRole(String data){
        logger.info("listRole原始入参data={}",data);
        Response response = new Response();
        Role wheres = JsonUtils.parseObject(data,Role.class);
        PageInfo pageInfo = JsonUtils.parseObject(data,PageInfo.class);
        if (pageInfo != null && pageInfo.getPageNum() != null && pageInfo.getPageSize() != null){
            List<String> orderColumns = new ArrayList<>();
            orderColumns.add("CREATED_TIME");
            List<Role> roleList = roleDao.select(wheres,orderColumns,false,pageInfo);

            Map<String,Object> resultMap = new HashMap<>();

            Long dataCount = roleDao.selectCount(wheres);
            pageInfo.setTotal(dataCount);
            pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
            resultMap.put("page_info",pageInfo);
            resultMap.put("list",roleList);
            response.setResultCodeAndMessageAndResult("0","成功",JsonUtils.toJsonString(resultMap));
        }else {
            List<Role> roleList = roleDao.select(wheres);
            response.setResultCodeAndMessageAndResult("0","成功",JsonUtils.toJsonString(roleList));
        }
        logger.info("listRole出参response={}",JsonUtils.toJsonString(response));

        return response;
    }


    /**
     * yyt.sys.role.resource.tree.list
     * 获取角色的资源树
     * @param data
     * @return
     */
    public Response listRoleResourceTree(String data){
        logger.info("listRoleResource原始入参data={}",data);
        Response response = new Response();
        RoleResourceRelation requestVo = JsonUtils.parseObject(data,RoleResourceRelation.class);

        List<RoleResourceRelation> list = resourceRelationDao.select(requestVo);
        List<Resource> allList = new ArrayList<>();
        for(RoleResourceRelation relation :list){
            allList.addAll(resourceDao.listResourceByLeaf(relation.getResourceId()));
        }

        allList = removeDuplicate(allList);
        List<Resource> treeList = resourceService.generateTree(allList);

        response.setResult(JsonUtils.toJsonString(treeList));
        return response;
    }

    public static List<Resource> removeDuplicate(List<Resource> list){
        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                if  (list.get(j).getId().equals(list.get(i).getId()))  {
                    list.remove(j);
                }
            }
        }
        return list;
    }


    /**
     * yyt.sys.role.resource.list
     * 获取角色的资源
     * @param data
     * @return
     */
    public Response listRoleResource(String data){
        logger.info("listRoleResource原始入参data={}",data);
        Response response = new Response();
        RoleResourceRelation requestVo = JsonUtils.parseObject(data,RoleResourceRelation.class);

        List<RoleResourceRelation> list = resourceRelationDao.select(requestVo);
        response.setResult(JsonUtils.toJsonString(list));
        return response;
    }

    /**
     * 删除角色 yyt.sys.role.delete
     * @param data
     * @return
     */
    public Response deleteRole(String data){
        Response response =new Response();
        Role requestVo  = JsonUtils.parseObject(data, Role.class);
        try {
            roleDao.delete(requestVo);
            resourceRelationDao.deleteByRoleId(requestVo.getId());
            response.setResultCodeAndMessage("0", "删除成功");
        }catch (Exception e){
            response.setResultCodeAndMessage("-1", "删除失败");
        }
        return  response;
    }

    /**
     * yyt.sys.role.by.account.select
     * @param data
     * @return
     */
    public Response selectRoleByAccount(String data){
        Response response =new Response();
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            String userId = jsonObject.getString("user_id");
            List<Role> roleList = roleDao.selectRoleByAccount(userId);
            response.setResultCodeAndMessageAndResult("0","成功",JsonUtils.toJsonString(roleList));
            return response;
        }catch (Exception e){
            logger.error("根据用户查询角色失败 errMsg={}",e);
            response.setResultCodeAndMessage("-1","根据用户查询角色失败");
            return response;
        }

    }


    /**
     * yyt.sys.role.resource.auth.get
     * 获取用户资源的动作
     * @param data {"resource_id":""}
     * @return
     */
    public Response getRoleResourceAuth(String data,String sessionId){
        logger.info("getRoleResourceAuth={}",data);
        Response response = new Response();

        SessionInfo sessionInfo = CacheService.getSessionInfo(sessionId);
        if(sessionInfo == null || cn.yunyichina.utils.commons.StringUtils.isBlank(sessionInfo.getInsuranceLoginName())){
            response.setResultCodeAndMessage("-1","用户未登录或已超时，请先登录");
            return response;
        }
        String userId = sessionInfo.getUserId();


        RoleResourceRelation requestVo = JsonUtils.parseObject(data,RoleResourceRelation.class);
        if(StringUtils.isBlank(requestVo.getResourceId())){
            response.setResultCodeAndMessage("-1","resourceId不能为空");
            return response;
        }

        List<Role> roleList = roleDao.selectRoleByAccount(userId);
        String auth = "";
        for(Role role:roleList) {
            requestVo.setRoleId(role.getId());
            List<RoleResourceRelation> list = resourceRelationDao.select(requestVo);
            if(!CollectionUtils.isEmpty(list)) {
                auth += list.get(0).getAuth();
            }
        }
        Map<String,String> map = new HashMap<>();
        map.put("auth",auth);
        response.setResult(JsonUtils.toJsonString(map));
        return response;
    }

}
